<template>
  <div class="case-detail-page" v-loading="loading">
    <div class="page-header">
      <el-button @click="$router.back()" class="back-btn">
        <el-icon><ArrowLeft /></el-icon>
        返回
      </el-button>
      <h2>案件详情</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleEdit">编辑案件</el-button>
        <el-dropdown @command="handleStatusChange">
          <el-button type="success">
            更新状态
            <el-icon><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="pending">待处理</el-dropdown-item>
              <el-dropdown-item command="processing">处理中</el-dropdown-item>
              <el-dropdown-item command="completed">已完成</el-dropdown-item>
              <el-dropdown-item command="closed">已关闭</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <div class="case-content" v-if="caseData">
      <el-row :gutter="20">
        <el-col :span="16">
          <!-- 基本信息 -->
          <div class="card">
            <h3>基本信息</h3>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="案件编号">{{ caseData.caseNumber }}</el-descriptions-item>
              <el-descriptions-item label="案件类型">{{ caseData.type }}</el-descriptions-item>
              <el-descriptions-item label="案件标题" :span="2">{{ caseData.title }}</el-descriptions-item>
              <el-descriptions-item label="案件状态">
                <el-tag :type="getStatusTagType(caseData.status)">
                  {{ getStatusText(caseData.status) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="优先级">
                <el-tag :type="getPriorityTagType(caseData.priority)">
                  {{ getPriorityText(caseData.priority) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="客户">{{ caseData.clientName }}</el-descriptions-item>
              <el-descriptions-item label="负责律师">{{ caseData.lawyerName }}</el-descriptions-item>
              <el-descriptions-item label="案件金额">
                {{ caseData.amount ? formatMoney(caseData.amount) : '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="开始日期">
                {{ formatDate(caseData.startDate, 'YYYY-MM-DD') }}
              </el-descriptions-item>
              <el-descriptions-item label="结束日期">
                {{ caseData.endDate ? formatDate(caseData.endDate, 'YYYY-MM-DD') : '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="创建时间">
                {{ formatDate(caseData.createdAt) }}
              </el-descriptions-item>
              <el-descriptions-item label="案件描述" :span="2">
                <div class="description">{{ caseData.description }}</div>
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 案件进展 -->
          <div class="card">
            <div class="card-header">
              <h3>案件进展</h3>
              <el-button type="primary" size="small" @click="handleAddProgress">
                添加进展
              </el-button>
            </div>
            <el-timeline>
              <el-timeline-item
                v-for="item in progressList"
                :key="item.id"
                :timestamp="formatDate(item.createdAt)"
                placement="top"
              >
                <el-card>
                  <h4>{{ item.title }}</h4>
                  <p>{{ item.content }}</p>
                  <div class="progress-meta">
                    <span>操作人：{{ item.operatorName }}</span>
                  </div>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </div>
        </el-col>

        <el-col :span="8">
          <!-- 相关文档 -->
          <div class="card">
            <div class="card-header">
              <h3>相关文档</h3>
              <el-button type="primary" size="small" @click="handleUploadDoc">
                上传文档
              </el-button>
            </div>
            <div class="document-list">
              <div
                v-for="doc in documentList"
                :key="doc.id"
                class="document-item"
                @click="handleDownloadDoc(doc)"
              >
                <el-icon><Document /></el-icon>
                <div class="doc-info">
                  <div class="doc-name">{{ doc.name }}</div>
                  <div class="doc-meta">
                    {{ formatFileSize(doc.size) }} | {{ formatDate(doc.createdAt, 'MM-DD HH:mm') }}
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 相关合同 -->
          <div class="card">
            <div class="card-header">
              <h3>相关合同</h3>
              <el-button type="primary" size="small" @click="handleLinkContract">
                关联合同
              </el-button>
            </div>
            <div class="contract-list">
              <div
                v-for="contract in contractList"
                :key="contract.id"
                class="contract-item"
                @click="handleViewContract(contract)"
              >
                <div class="contract-info">
                  <div class="contract-title">{{ contract.title }}</div>
                  <div class="contract-meta">
                    {{ contract.contractNumber }} | {{ formatMoney(contract.amount) }}
                  </div>
                </div>
                <el-tag :type="getContractStatusTagType(contract.status)">
                  {{ getContractStatusText(contract.status) }}
                </el-tag>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 编辑案件对话框 -->
    <CaseForm
      v-model:visible="editVisible"
      :form-data="caseData"
      @success="handleEditSuccess"
    />

    <!-- 添加进展对话框 -->
    <ProgressForm
      v-model:visible="progressVisible"
      :case-id="caseId"
      @success="handleProgressSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCaseDetail, updateCaseStatus } from '@/api/case'
import { formatDate, formatMoney, formatFileSize } from '@/utils'
import type { Case, Document, Contract } from '@/types'
import CaseForm from './components/CaseForm.vue'
import ProgressForm from './components/ProgressForm.vue'

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const editVisible = ref(false)
const progressVisible = ref(false)
const caseData = ref<Case | null>(null)
const progressList = ref<any[]>([])
const documentList = ref<Document[]>([])
const contractList = ref<Contract[]>([])

const caseId = route.params.id as string

// 获取案件详情
const fetchCaseDetail = async () => {
  try {
    loading.value = true
    const data = await getCaseDetail(caseId)
    caseData.value = data.case
    progressList.value = data.progressList || []
    documentList.value = data.documentList || []
    contractList.value = data.contractList || []
  } catch (error) {
    ElMessage.error('获取案件详情失败')
    router.back()
  } finally {
    loading.value = false
  }
}

// 编辑案件
const handleEdit = () => {
  editVisible.value = true
}

// 编辑成功
const handleEditSuccess = () => {
  fetchCaseDetail()
}

// 更新状态
const handleStatusChange = async (status: string) => {
  try {
    await ElMessageBox.confirm(`确定要将案件状态更新为"${getStatusText(status)}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await updateCaseStatus(caseId, status)
    ElMessage.success('状态更新成功')
    fetchCaseDetail()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('状态更新失败')
    }
  }
}

// 添加进展
const handleAddProgress = () => {
  progressVisible.value = true
}

// 进展添加成功
const handleProgressSuccess = () => {
  fetchCaseDetail()
}

// 上传文档
const handleUploadDoc = () => {
  // TODO: 实现文档上传功能
  ElMessage.info('文档上传功能开发中')
}

// 下载文档
const handleDownloadDoc = (doc: Document) => {
  // TODO: 实现文档下载功能
  ElMessage.info('文档下载功能开发中')
}

// 关联合同
const handleLinkContract = () => {
  // TODO: 实现合同关联功能
  ElMessage.info('合同关联功能开发中')
}

// 查看合同
const handleViewContract = (contract: Contract) => {
  router.push(`/contracts/detail/${contract.id}`)
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    pending: 'warning',
    processing: 'primary',
    completed: 'success',
    closed: 'info'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    pending: '待处理',
    processing: '处理中',
    completed: '已完成',
    closed: '已关闭'
  }
  return textMap[status] || status
}

// 获取优先级标签类型
const getPriorityTagType = (priority: string) => {
  const typeMap: Record<string, string> = {
    low: 'info',
    medium: 'warning',
    high: 'danger',
    urgent: 'danger'
  }
  return typeMap[priority] || 'info'
}

// 获取优先级文本
const getPriorityText = (priority: string) => {
  const textMap: Record<string, string> = {
    low: '低',
    medium: '中',
    high: '高',
    urgent: '紧急'
  }
  return textMap[priority] || priority
}

// 获取合同状态标签类型
const getContractStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    draft: 'info',
    reviewing: 'warning',
    approved: 'primary',
    signed: 'success',
    expired: 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取合同状态文本
const getContractStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    draft: '草稿',
    reviewing: '审核中',
    approved: '已批准',
    signed: '已签署',
    expired: '已过期'
  }
  return textMap[status] || status
}

onMounted(() => {
  fetchCaseDetail()
})
</script>

<style lang="scss" scoped>
.case-detail-page {
  .page-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    
    .back-btn {
      margin-right: 16px;
    }
    
    h2 {
      flex: 1;
      margin: 0;
    }
    
    .header-actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .case-content {
    .card {
      background: #fff;
      border-radius: 8px;
      padding: 20px;
      margin-bottom: 20px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      
      h3 {
        margin: 0 0 16px 0;
        font-size: 16px;
        font-weight: 600;
      }
      
      .card-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 16px;
        
        h3 {
          margin: 0;
        }
      }
      
      .description {
        line-height: 1.6;
        white-space: pre-wrap;
      }
    }
    
    .progress-meta {
      margin-top: 8px;
      font-size: 12px;
      color: #909399;
    }
    
    .document-list {
      .document-item {
        display: flex;
        align-items: center;
        padding: 12px;
        border: 1px solid #e4e7ed;
        border-radius: 4px;
        margin-bottom: 8px;
        cursor: pointer;
        transition: all 0.3s;
        
        &:hover {
          background: #f5f7fa;
          border-color: #409eff;
        }
        
        .el-icon {
          font-size: 24px;
          color: #409eff;
          margin-right: 12px;
        }
        
        .doc-info {
          flex: 1;
          
          .doc-name {
            font-weight: 500;
            margin-bottom: 4px;
          }
          
          .doc-meta {
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }
    
    .contract-list {
      .contract-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 12px;
        border: 1px solid #e4e7ed;
        border-radius: 4px;
        margin-bottom: 8px;
        cursor: pointer;
        transition: all 0.3s;
        
        &:hover {
          background: #f5f7fa;
          border-color: #409eff;
        }
        
        .contract-info {
          flex: 1;
          
          .contract-title {
            font-weight: 500;
            margin-bottom: 4px;
          }
          
          .contract-meta {
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }
  }
}
</style>
